package Utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileUtils{
	public static void writeFile(String content,String path,String charset){
		BufferedWriter out=null;
		try{
			if(charset.equals(""))
				out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path,false),"UTF-8"));
			else
				out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path,false),charset));
			out.write(content);
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(out!=null)try{out.close();}catch (Exception e) {}
		}
	}
	public final static boolean copyFile(File fr, File ft) {
		FileInputStream from = null;
		FileOutputStream to = null;
		try {
			from = new FileInputStream(fr);
			to = new FileOutputStream(ft);
			byte[] buffer = new byte[1024];
			int bytesRead;
			while ((bytesRead = from.read(buffer)) != -1)
				to.write(buffer, 0, bytesRead);
			from.close();
			to.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally{
			if(from!=null)try{from.close();}catch (Exception e) {}
			if(to!=null)try{to.close();}catch (Exception e) {}
		}
	}
	

	/**deleteDir function
	 * Des:Deletes all files and subdirectories under dir.
	 * 	   Returns true if all deletions were successful.
	 * 	   iff a deletion fails, the method stops attempting to delete and returns false. 	
	 * @param dir
	 * @return
	 */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // The directory is now empty so delete it
        return dir.delete();
    }
    public static String readFile(String path){
		BufferedReader in = null; 
		String content = "";
		try{	
			in =new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
			String line="";
			while((line=in.readLine())!=null){
				content+=line+"\n\r";
			}
		}catch (Exception e) {
			System.out.println("File not found: "+path);
		}finally{
			if(in!=null) try{in.close();}catch (Exception e) {
			}
		}
		return content;
	}
}